import * as vscode from 'vscode';
import { keywordMap, KeywordMapping } from './keywords';



export function activate(context: vscode.ExtensionContext) {
    console.log('Chinese Keyword Decorator 已激活');

    let activeEditor = vscode.window.activeTextEditor;
    let decorationType: vscode.TextEditorDecorationType | undefined;
    // 存储当前失效的装饰器位置（临时状态）
    let currentDisabledDecoration: string | null = null;

    // 生成装饰器位置唯一标识
    function getDecorationKey(range: vscode.Range, keyword: string): string {
        return `${range.start.line}:${range.start.character}:${range.end.line}:${range.end.character}:${keyword}`;
    }

    // 获取配置和合并后的关键字映射
    function getConfigAndMergedMap(): {
        config: vscode.WorkspaceConfiguration;
        mergedKeywordMap: { [key: string]: KeywordMapping };
        regexPrefix: string;
        regexSuffix: string;
    } {
        const config = vscode.workspace.getConfiguration('chineseKeywordDecorator');
        const regexPrefix = config.get<string>('regexPrefix', "(?<=^|\\s)");
        const regexSuffix = config.get<string>('regexSuffix', "(?![\\w'\":\\-=])");
        const customKeywords = config.get<{ [key: string]: string | KeywordMapping }>('customKeywords', {});
        const excludedKeywords = config.get<string[]>('excludedKeywords', []);
        const mergedKeywordMap: { [key: string]: KeywordMapping } = { ...keywordMap };

        // 合并自定义关键字
        Object.keys(customKeywords).forEach(key => {
            const customValue = customKeywords[key];
            if (typeof customValue === 'string') {
                mergedKeywordMap[key] = { text: customValue };
            } else {
                mergedKeywordMap[key] = customValue as KeywordMapping;
            }
        });

        // 剔除排除的关键字
        excludedKeywords.forEach(keyword => {
            if (mergedKeywordMap[keyword]) {
                delete mergedKeywordMap[keyword];
            }
        });

        return { config, mergedKeywordMap, regexPrefix, regexSuffix };
    }

    // 检查位置是否在注释中
    function isInComment(document: vscode.TextDocument, position: vscode.Position): boolean {
        const lineText = document.lineAt(position.line).text;
        const textBeforePosition = lineText.substring(0, position.character);

        // 检查单行注释
        if (textBeforePosition.includes('//')) {
            const commentStart = textBeforePosition.lastIndexOf('//');
            // 确保 // 不在字符串中
            const textBeforeComment = textBeforePosition.substring(0, commentStart);
            const stringQuoteCount = (textBeforeComment.match(/"/g) || []).length;
            return stringQuoteCount % 2 === 0; // 不在字符串中
        }

        // 检查多行注释（简化版本）
        const textUpToPosition = document.getText(new vscode.Range(new vscode.Position(0, 0), position));
        const multiLineCommentStart = textUpToPosition.lastIndexOf('/*');
        const multiLineCommentEnd = textUpToPosition.lastIndexOf('*/');

        // 如果存在未闭合的多行注释
        if (multiLineCommentStart > multiLineCommentEnd) {
            return true;
        }

        return false;
    }

    /**
     *  查找所有关键字匹配的位置（排除注释中的匹配）     * 
     * @param text 文本内容
     * @param mergedKeywordMap 所有的关键字映射集合
     * @param regexPrefix 关键字前缀正则表达式
     * @param regexSuffix 关键字后缀正则表达式
     * @returns 
     */
    function findKeywordMatches(text: string, mergedKeywordMap: { [key: string]: KeywordMapping }, regexPrefix: string, regexSuffix: string): Array<{ keyword: string; range: vscode.Range }> {
        const matches: Array<{ keyword: string; range: vscode.Range }> = [];
        const currentFileName = activeEditor?.document.fileName || '';
        const currentFileSuffix = currentFileName.includes('.') ? currentFileName.split('.').pop()?.toLowerCase() : '';

        Object.keys(mergedKeywordMap).forEach(keyword => {
            const mapping = mergedKeywordMap[keyword];
            
            // 检查fileSuffix，如果配置了文件后缀，则只在匹配的文件中生效
            if (mapping.fileSuffix && currentFileSuffix) {
                const suffixes = mapping.fileSuffix.toLowerCase().split(',').map(s => s.trim());
                if (!suffixes.includes(currentFileSuffix)) {
                    return; // 跳过不匹配文件后缀的关键字
                }
            }

            const regex = new RegExp(`${regexPrefix}${keyword}${regexSuffix}`, 'g');
            let match;

            while ((match = regex.exec(text)) !== null) {
                const startPos = activeEditor!.document.positionAt(match.index);

                // 检查是否在注释中，如果不在注释中才添加到匹配列表
                if (!isInComment(activeEditor!.document, startPos)) {
                    const endPos = activeEditor!.document.positionAt(match.index + match[0].length);
                    matches.push({
                        keyword,
                        range: new vscode.Range(startPos, endPos)
                    });
                }
            }
        });

        return matches;
    }

    // 处理装饰器点击事件
    function handleDecorationClick(event: vscode.TextEditorSelectionChangeEvent) {
        if (!activeEditor || event.textEditor !== activeEditor) {
            return;
        }

        const selection = event.selections[0];
        if (!selection.isEmpty) {
            return;
        }

        // 检查点击位置是否在装饰器范围内
        const clickedPosition = selection.active;
        const text = activeEditor.document.getText();

        const { mergedKeywordMap, regexPrefix, regexSuffix } = getConfigAndMergedMap();
        const matches = findKeywordMatches(text, mergedKeywordMap, regexPrefix, regexSuffix);

        for (const match of matches) {
            // 检查点击位置是否在当前装饰器范围内
            if (clickedPosition.isAfterOrEqual(match.range.start) && clickedPosition.isBeforeOrEqual(match.range.end)) {
                const decorationKey = getDecorationKey(match.range, match.keyword);
                currentDisabledDecoration = decorationKey;
                updateDecorations();
                return;
            }
        }
    }

    // 更新装饰器
    function updateDecorations() {
        if (!activeEditor) {
            return;
        }

        // 清除之前的装饰器
        if (decorationType) {
            decorationType.dispose();
        }

        // 获取配置
        const config = vscode.workspace.getConfiguration('chineseKeywordDecorator');
        const showOriginalKeyword = config.get<boolean>('showOriginalKeyword', true);
        const defaultColor = config.get<string>('defaultColor', '#cc99cd');
        const supportedLanguages = config.get('supportedLanguages', ['javascript', 'typescript', 'vue']);

        if (!supportedLanguages.includes(activeEditor.document.languageId)) {
            return;
        }
        // 根据配置创建不同的装饰器类型
        if (showOriginalKeyword) {
            // 显示原始关键字，在右侧显示中文翻译
            decorationType = vscode.window.createTextEditorDecorationType({
                after: {
                    color: defaultColor,
                    //fontStyle: 'italic',
                    //margin: '0 0 0 0.5em'
                }
            });
        } else {
            // 隐藏原始关键字，在左侧显示中文翻译
            // 使用零宽度空格和透明文本来实现隐藏效果
            decorationType = vscode.window.createTextEditorDecorationType({
                after: {
                    color: defaultColor,
                    //fontStyle: 'italic'
                },
                textDecoration: 'none; opacity: 0.01; font-size: 0.1px;'
            });
        }

        const text = activeEditor.document.getText();
        const decorations: vscode.DecorationOptions[] = [];

        const { mergedKeywordMap, regexPrefix, regexSuffix } = getConfigAndMergedMap();
        const matches = findKeywordMatches(text, mergedKeywordMap, regexPrefix, regexSuffix);

        for (const match of matches) {
            const decorationKey = getDecorationKey(match.range, match.keyword);

            // 检查装饰器是否当前被临时禁用
            if (decorationKey !== currentDisabledDecoration) {
                const mapping = mergedKeywordMap[match.keyword];
                const textColor = mapping.color || defaultColor;

                const decoration: vscode.DecorationOptions = {
                    range: match.range,
                    renderOptions: showOriginalKeyword ? {
                        after: {
                            contentText: mapping.text,
                            color: textColor,
                            // fontStyle: 'italic',
                            // margin: '0 0 0 0.5em'
                        }
                    } : {
                        after: {
                            contentText: mapping.text,
                            color: textColor,
                            // fontStyle: 'italic'
                        }
                    }
                };

                decorations.push(decoration);
            }
        }

        activeEditor.setDecorations(decorationType, decorations);
    }

    // 编辑器切换时更新
    vscode.window.onDidChangeActiveTextEditor(editor => {
        // 重置临时失效状态
        currentDisabledDecoration = null;
        activeEditor = editor;
        if (editor) {
            updateDecorations();
        }
    }, null, context.subscriptions);

    // 文档内容变化时更新（使用防抖优化）
    let debounceTimer: NodeJS.Timeout | undefined;
    vscode.workspace.onDidChangeTextDocument(event => {
        if (activeEditor && event.document === activeEditor.document) {
            // 清除之前的定时器
            if (debounceTimer) {
                clearTimeout(debounceTimer);
            }
            // 设置新的防抖定时器（延迟 150ms 执行）
            debounceTimer = setTimeout(() => {
                // 重置临时失效状态
                currentDisabledDecoration = null;
                updateDecorations();
            }, 500);
        }
    }, null, context.subscriptions);

    // 初始更新
    if (activeEditor) {
        updateDecorations();
    }

    // 注册点击事件监听
    const clickDisposable = vscode.window.onDidChangeTextEditorSelection(handleDecorationClick);
    context.subscriptions.push(clickDisposable);

    // 注册重置命令（临时失效不需要重置功能）
    const resetDisposable = vscode.commands.registerCommand('chinese-keyword-decorator.reset', () => {
        currentDisabledDecoration = null;
        updateDecorations();
    });

    // 注册切换命令
    const toggleDisposable = vscode.commands.registerCommand('chinese-keyword-decorator.toggle', () => {
        vscode.window.showInformationMessage('Chinese Keyword Decorator 已切换');
    });

    context.subscriptions.push(resetDisposable, toggleDisposable);
}

export function deactivate() { }